package com.jvm.demo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Objects;

public class HelloClassLoader extends ClassLoader {

    public static void main(String[] args) throws Exception {
//        new HelloClassLoader().findClass("com.jvm.demo.HelloByteCode").newInstance();
        new HelloClassLoader().findClass("Hello").newInstance();
        System.out.println("执行结束");
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
//        String helloBase64 = "yv66vgAAADQAIQoABwATCQAUABUKAAYAFgoAFwAYBEOWAAAHABkHABoBAAY8aW5pdD4BAAMoKVYBAARDb2RlAQAPTGluZU51bWJlclRhYmxlAQAEbWFpbgEAFihbTGphdmEvbGFuZy9TdHJpbmc7KVYBAAR0ZXN0AQADKClGAQANU3RhY2tNYXBUYWJsZQEAClNvdXJjZUZpbGUBABJIZWxsb0J5dGVDb2RlLmphdmEMAAgACQcAGwwAHAAdDAAOAA8HAB4MAB8AIAEAGmNvbS9qdm0vZGVtby9IZWxsb0J5dGVDb2RlAQAQamF2YS9sYW5nL09iamVjdAEAEGphdmEvbGFuZy9TeXN0ZW0BAANvdXQBABVMamF2YS9pby9QcmludFN0cmVhbTsBABNqYXZhL2lvL1ByaW50U3RyZWFtAQAHcHJpbnRsbgEABChGKVYAIQAGAAcAAAAAAAMAAQAIAAkAAQAKAAAAHQABAAEAAAAFKrcAAbEAAAABAAsAAAAGAAEAAAADAAkADAANAAEACgAAACYAAgABAAAACrIAArgAA7YABLEAAAABAAsAAAAKAAIAAAAGAAkABwAJAA4ADwABAAoAAABhAAIAAgAAACAMQwM8GxBkogAXIhuGYkMiEgWVngAFIq6EAQGn/+kirgAAAAIACwAAAB4ABwAAAAoAAgALAAoADAAPAA0AFgAOABgACwAeABEAEAAAAAsAA/0ABAIBE/oABQABABEAAAACABI=";
//        byte[] resolveBytes = decode(helloBase64);
//        return defineClass(name, resolveBytes, 0, bytes.length);

        byte[] bytes = null;
        try {
            bytes = Files.readAllBytes(new File(System.getProperty("user.dir") + "/src/com/jvm/demo/Hello.xlass").toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] resolveBytes = null;
        if (Objects.nonNull(bytes)) {
            resolveBytes = new byte[bytes.length];
            for (int i = 0; i < bytes.length; i++) {
                byte readByte = bytes[i];
                resolveBytes[i] = (byte) (255 - readByte);
            }
        }

        return defineClass(name, resolveBytes, 0, bytes.length);
    }

    public byte[] decode(String base64Str) {
        return Base64.getDecoder().decode(base64Str);
    }

}
